package utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * the native News Video can not run from the jar, So is need to extract this
 * video to play in a parent directory. This class extract this video to the
 * right palce.
 * 
 * @author Heitor Meira de Melo
 * @version 0.1 December 03, 2009.
 * 
 */
public class ExtractVideo {
	private InputStream is = null;
	private OutputStream os = null;

	/**
	 * Provides the parent directory.
	 * 
	 * @return A string with the path of the parent directory
	 */
	private String parentPath() {
		String path = Class.class.getResource("/bailey.flv").toString();
		path = path.replaceFirst("jar:file:", "");
		path = path.replaceFirst(".jar!/bailey.flv", "");
		return path;
	}

	/**
	 * Provides the directory where the news video is.
	 * 
	 * @return A string with the path of the parent directory
	 */
	private String currentPath() {
		String path = Class.class.getResource("/bailey.flv").toString();
		path = path.replaceFirst("jar:file:", "");
		path = path.replaceFirst("!/bailey.flv", "");
		return path;
	}

	public void extractVideo() {
		try {
			ZipFile zf = new ZipFile(currentPath());
			System.out.println();
			File fl = new File(parentPath());

			File arquivo;

			Enumeration e = zf.entries();
			while (e.hasMoreElements()) {
				ZipEntry entrada = (ZipEntry) e.nextElement();
				arquivo = new File(fl, entrada.getName());

				if (!arquivo.getName().equals("bailey.flv")) {
					continue;
				}
				fl.mkdirs();

				try {
					int TAMANHO_BUFFER = 2048;
					byte[] buffer = new byte[TAMANHO_BUFFER];
					is = zf.getInputStream(entrada);
					os = new FileOutputStream(arquivo);

					int bytesLidos = 0;

					while ((bytesLidos = is.read(buffer)) > 0) {
						os.write(buffer, 0, bytesLidos);
					}
				} finally {
					if (is != null) {
						try {
							is.close();
						} catch (Exception ex) {
						}
					}
					if (os != null) {
						try {
							os.close();
						} catch (Exception ex) {
						}
					}
				}
			}
			zf.close();
		} catch (Exception ex) {

		}
	}
}
